package com.gitee.tianchaohongyu.jdcl.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;

import java.lang.reflect.UndeclaredThrowableException;

/**
 * 语言工具类
 */
public class LangUtils {

  private static final Logger logger = LoggerFactory.getLogger(LangUtils.class);

  /**
   * 忽略某类异常
   *
   * @param <R> 返回类型
   * @return
   */
  @Nullable
  public static <R> R ignore(Class<? extends Exception> exception, ThrowsRunnable<R> fn) {
    try {
      return fn.invok();
    } catch (Throwable e) {
      if (exception.isAssignableFrom(e.getClass())) {
        logger.debug(String.format("成功忽略:%s", e));
        return null;  //要求忽略的异常
      }
      if (e instanceof RuntimeException) throw (RuntimeException) e; //运行时异常
      throw new UndeclaredThrowableException(e);  //要求检查的异常,包装后抛出
    }
  }

  /**
   * 可抛出异常的函数
   *
   * @param <R>
   */
  interface ThrowsRunnable<R> {

    /**
     * 调用
     *
     * @return 返回结果
     */
    R invok() throws Throwable;
  }
}
